var express = require('express');
var crypto = require('crypto');
var router = express.Router();
var userTest = require('../../db.json');
var ticketData = {};//这个数据需要写入redis，否则应用重启后，数据会丢失


router.get('/get-ticket', function(req, res) {
    res.jsonp({ticket:req.cookies.ticket});
});

router.get('/get-uid',function(req, res) {
    var ticket = req.query.ticket;
    var uid = ticketData[ticket];
    res.send({uid:uid});
});

router.get('/login',function(req, res) {
    res.render('login');
});

router.post('/login',function(req, res) {
    var _body = req.body;
    var username = _body.username;
    var password = _body.password;

    if (username !== userTest.account || password !== userTest.password) {
        return res.send({code:1,msg:'用户名或者密码错误'});
    }
    crypto.randomBytes(16,function(err,bytes) {
        if (err) {
            console.error('生成随机数失败',err);
            return res.send({code:2,msg:'生成凭证失败'});
        }
        var ticket = bytes.toString('hex');
        res.set('P3P','CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');

        res.cookie('ticket',ticket);
        ticketData[ticket] = userTest.uid;

        res.send({code:0});
    });
    
});

module.exports = router;
